package com.gzy.wbapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.TypeReference;
import com.gzy.wbapplication.events.LoginCompleteEvent;
import com.gzy.wbapplication.model.Result;
import com.gzy.wbapplication.net.AuthApi;
import com.gzy.wbapplication.net.core.XXModelCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import okhttp3.Call;

public class SignupActivity extends AppCompatActivity {
    EditText edt_username;
    EditText edt_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);

        findViewById(R.id.tv_jump2login).setOnClickListener(view -> {
            startActivity(new Intent(this,LoginActivity.class));
        });
        findViewById(R.id.back).setOnClickListener(view -> {
            finish();
        });
        findViewById(R.id.btn_signup).setOnClickListener(view -> {
            signup();
        });

        edt_username = findViewById(R.id.edt_username);
        edt_password = findViewById(R.id.edt_password);

        EventBus.getDefault().register(this);

    }

    private void signup() {
        // 注册

        String username = edt_username.getText().toString();
        String password = edt_password.getText().toString();

        if (TextUtils.isEmpty(username)){
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)){
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        AuthApi.signup(username, password, new XXModelCallback<Result<String>>(new TypeReference<Result<String>>(){}) {
            @Override
            public void onResponseData(Call call, Result<String> model) {
                Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure2(Call call, IOException e, ErrType type, String message) {
                Toast.makeText(getApplicationContext(), "注册失败:" + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(LoginCompleteEvent message) {
        finish();
    }
}
